# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

transition_to_low_se_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_transition_to_low_se.rds" #nolint
    )
setnames(transition_to_low_se_dt, "ref_event_time", "event_time")
transition_to_low_se_dt <- transition_to_low_se_dt[event_time == 99]

transition_to_high_se_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_transition_to_high_se.rds" #nolint
    )
setnames(transition_to_high_se_dt, "ref_event_time", "event_time")
transition_to_high_se_dt <-
    transition_to_high_se_dt[event_time == 99]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-5.2.tex"
file.create(filedir)

# Start Table 5.2
start_latex_table(
    column_structure = "ccccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  &  & \\multicolumn{4}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 4,
    end_col = 7,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Outcome} & \\multirow{3}{*}{Value} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & & Pre-Win Income  &  Pre-Win Income "
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & & (1) & & (2)  &  (3) "
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Add body of Table 5.2
# - introduce convenience functions given a similar structure throughout

Table52Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "\\multirow{4}{*}{%s} & Estimate & & %s & & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table52Row2 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Standard Error & & (%s) & & (%s) & (%s)",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table52Row3 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Counterfactual Mean & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table52Row4 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Percentage Change & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}


# Transition to Low-Paying SE
Table52Row1(
    dt = transition_to_low_se_dt,
    text = "Transition to Low-Paying SE",
    scaler = 100000
)
Table52Row2(
    dt = transition_to_low_se_dt,
    scaler = 100000
)
Table52Row3(
    dt = transition_to_low_se_dt,
    scaler = 1
)
Table52Row4(
    dt = transition_to_low_se_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Transition to High-Paying SE
Table52Row1(
    dt = transition_to_high_se_dt,
    text = "Transition to High-Paying SE",
    scaler = 100000
)
Table52Row2(
    dt = transition_to_high_se_dt,
    scaler = 100000
)
Table52Row3(
    dt = transition_to_high_se_dt,
    scaler = 1
)
Table52Row4(
    dt = transition_to_high_se_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table 5.2
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
transition_to_low_se_dt <- NULL
transition_to_high_se_dt <- NULL
rm(
    transition_to_low_se_dt,
    transition_to_high_se_dt
)